package cn.toprog.viewer.util;

import cn.toprog.viewer.component.Thumbnail;
import java.io.File;
import java.nio.file.Files;
import javafx.scene.layout.Pane;
import javafx.scene.shape.Rectangle;

/**
 * 项目名称: TaoImagerViewer
 * 创建时间: 2021/4/8 12:08
 * 作者姓名: xiaolei
 */

public class Utilities {
    public static boolean isImageFile(File file) {
        if (file.isFile() && Files.isReadable(file.toPath())) {
            String filename = file.getName().toLowerCase();
            String extName = filename.substring(filename.lastIndexOf('.'));
            if (".png".equals(extName) || ".jpg".equals(extName) || ".jpeg".equals(extName) || ".gif".equals(extName) || ".bmp".equals(extName)) {
                return true;
            }
        }
        return false;
    }

    public static boolean isIntersected(Thumbnail thumbnail, double x1, double y1, double x2, double y2) {
        double lef = x1 > x2 ? x2 : x1;
        double rig = x1 < x2 ? x2 : x1;
        double top = y1 > y2 ? y2 : y1;
        double bot = y1 < y2 ? y2 : y1;
        if (!(thumbnail.getLayoutX() + thumbnail.getWidth() < lef
                || thumbnail.getLayoutX() > rig
                || thumbnail.getLayoutY() + thumbnail.getHeight() < top
                || thumbnail.getLayoutY() > bot)) {
            return true;
        } else {
            return false;
        }

    }

    public static void fixedRectangle(Pane pane, Rectangle r, double x1, double y1, double x2, double y2) {
        if (x2 < 0) x2 = 0;
        if (x2 > pane.getWidth()) x2 = pane.getWidth() - 1;
        if (y2 < 0) y2 = 0;
        if (y2 > pane.getHeight()) y2 = pane.getHeight() - 1;

        double x = x1 < x2 ? x1 : x2;
        double y = y1 < y2 ? y1 : y2;
        r.setX(x < 0 ? 0 : x);
        r.setY(y < 0 ? 0 : y);
        r.setWidth(Math.abs(x1 - x2));
        r.setHeight(Math.abs(y1 - y2));
    }
}
